﻿using BootstrapBlazor.Components;
using BootstrapBlazorAutoComplete.Shared.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;

namespace BootstrapBlazorAutoComplete.Shared.Pages
{
    /// <summary>
    /// 
    /// </summary>
    public partial class TableDemo : ComponentBase
    {
        [Inject]
        [NotNull]
        private IStringLocalizer<Foo>? Localizer { get; set; }

        private readonly ConcurrentDictionary<Foo, IEnumerable<SelectedItem>> _cache = new();

        private IEnumerable<SelectedItem> GetHobbys(Foo item) => _cache.GetOrAdd(item, f => Foo.GenerateHobbys(Localizer));

        /// <summary>
        /// 
        /// </summary>
        private static IEnumerable<int> PageItemsSource => new int[] { 20, 40 };
        private static List<string> StaticItems => new() { "1", "12", "123", "1234", "12345", "123456", "abc", "abcdef", "ABC", "aBcDeFg", "ABCDEFG" };

        public static List<IValidator> RequiredRules { get; set; } = new() { new FormItemValidator(new RequiredAttribute() { ErrorMessage = "{0}不能为空！" }),
        new FormItemValidator(new InListStrAttribute(StaticItems){ErrorMessage="{0}必须在列表内!"})};

    }
    public class InListStrAttribute : ValidationAttribute
    {
        private List<string> _sourceValue;
        public InListStrAttribute(List<string> SourceValue)
        {
            _sourceValue = SourceValue;
        }

        public override bool IsValid(object? value)
        {
            if (value == null)
            {
                return false;
            }
            if (_sourceValue.Contains(value.ToString()))
                return true;
            return base.IsValid(value);
        }

        protected override ValidationResult IsValid(object? value, ValidationContext validationContext)
        {
            if (_sourceValue.Contains(value?.ToString()))
                return ValidationResult.Success;
            return new ValidationResult(ErrorMessage);
        }
    }
}